$(document).ready(function () {



    layui.use(function () {

        var layer = layui.layer;
        table = layui.table;
        // 表格
        form = layui.form;
        form.on('select(status)', function (data) {//监听状态查询
            $('div[lay-filter="search"]').click();
        });

        form.on('submit(search)', function (data) {//查询广播
            params = data.field;
            params.pageSize = 10;
            queryTable()
            return false;
        });

        form.on('select(tool-status)', function (data) {//监听状态查询

            $('div[lay-filter="searchAudio"]').click();
        });
        form.on('select(format)', function (data) {//监听状态查询

            $('div[lay-filter="searchAudio"]').click();
        });

        form.on('submit(searchAudio)', function (data) {//查询音频 

            params = data.field;
            params.pageSize = 10;
            queryAudioTable()
            return false;
        });


        form.on('submit(operateHorn-save)', function (data) {//播放音频

            var field = data.field

            var checkStatus = table.checkStatus('table');

            var checkedIds = checkStatus.data.map(item => item.deviceId);

            if (field.playType == 2) {
                params = {
                    "deviceIds": checkedIds,
                    "playType": field.playType,
                    "audioId": field.audioId,
                    "volume": field.volume
                }
            } else if (field.playType == 3) {
                params = {
                    "deviceIds": checkedIds,
                    "playType": field.playType,
                    "audioId": field.audioId,
                    "playCount": field.playCount,
                    "volume": field.volume
                }
            } else if (field.playType == 4) {
                params = {
                    "deviceIds": checkedIds,
                    "playType": field.playType,
                    "volume": field.volume
                }
            }

            operateHornAjax(params)



            return false;
        });



        form.on('submit(searchOperate)', function (data) {//查询历史操作

            params = data.field;
            params.pageSize = 10;
            queryOperateTable()
            return false;
        });



        initSubMenu();
        queryTable();


    });
})
var params = {};//查询条件参数
var form, unit, table;
var drawer;//抽屉实例
var curId = null;//当前选中物资ID

//查询物资类型列表
queryTable = () => {
    let toolWidth = window.innerWidth / 1920 * 150
    layui.use('table', function () {


        //展示已知数据
        table.render({
            elem: '#table'
            , text: {
                none: '暂无数据'
            }
            , method: 'get'
            , url: ajaxPrefix() + "/horn/list/status"
            , headers: {
                SessionId: JSON.parse(localStorage.getItem('sessionId'))
            }
            , where: params
            , parseData: function (res) { //res 即为原始返回的数据
                return {
                    "code": res.status == 200 ? 0 : 1, //解析接口状态
                    "msg": res.message, //解析提示文本
                    "count": res.result.total, //解析数据长度
                    "data": res.result.data //解析数据列表
                };
            }
            , request: {
                pageName: 'pageNum' //页码的参数名称，默认：page
                ,
                limitName: 'pageSize' //每页数据量的参数名，默认：limit
            }
            , cols: [[ //标题栏
                {
                    type: 'checkbox',
                    align: 'center',
                    width: 50,
                },
                { field: 'address', title: '设备名称', align: "center" }
                , { field: 'deviceCode', title: '设备编码', align: "center" }
                , { field: 'playStatusDesc', title: '播放状态', align: "center" }
                , { field: 'dataTime', title: '上报时间', align: "center" }
            ]]
            , height: 'full'
            // ,skin: 'line' //表格风格
            , even: true
            , page: { //支持传入 laypage 组件的所有参数（某些参数除外，如：jump/elem） - 详见文档
                layout: ['count', 'prev', 'page', 'next', 'skip'] //自定义分页布局
                //,curr: 5 //设定初始在第 5 页
                , groups: 3 //只显示 1 个连续页码
                , first: false //不显示首页
                , last: false //不显示尾页

            }
            , done: function (res, curr, count) {

                $('.layui-table-cell').height($('.contain-table-list').height() / 20);
            },

        });

    });
}




//音频列表弹窗
queryAudio = () => {
    curEvent = ""
    curDate = ""
    layer.open({
        title: '音频管理',
        type: 1,
        offset: 'r',
        move: false,
        anim: 'slideLeft', // 从右往左
        area: ['100%', '100%'],
        shade: 0.3,
        shadeClose: false,
        id: 'audio-offset',
        success: function (layero, index, that) {
            queryAudioTable()

            layui.laydate.render({
                elem: "#history-date",
                range: true,
                done: function (value, date, endDate) {
                    curDate = value
                    queryAudioTable()
                }
            });

            form.render();


            form.on('radio(event-filter)', function (data) {



                var value = data.elem.value;
                curEvent = value;
                queryAudioTable()

            });
        },
        content: $('#table-tool').html()
    });
}


// 查询音频列表
var curEvent = "", curDate = "";
function queryAudioTable() {

    if (curDate != '') {
        var beginTime = curDate.split(' - ')[0]
        var endTime = curDate.split(' - ')[1]
    } else {
        var beginTime = ''
        var endTime = ''
    }
    params.startDate = beginTime
    params.endDate = endTime

    table.render({
        elem: '#record-table'
        , text: {
            none: '暂无数据'
        }
        , method: 'get'
        , url: ajaxPrefix() + "/audio/list"
        , headers: {
            SessionId: JSON.parse(localStorage.getItem('sessionId'))
        }
        , where: params
        , parseData: function (res) { //res 即为原始返回的数据
            return {
                "code": res.status == 200 ? 0 : 1, //解析接口状态
                "msg": res.message, //解析提示文本
                "count": res.result.total, //解析数据长度
                "data": res.result.data
            };
        }
        , request: {
            pageName: 'pageNum' //页码的参数名称，默认：page
            ,
            limitName: 'pageSize' //每页数据量的参数名，默认：limit
        }
        , cols: [
            [ //表头
                {
                    type: 'checkbox',
                    align: 'center',
                    width: 50,
                }, {
                    field: 'name',
                    title: '音频名称',
                    align: 'center'
                }, {
                    field: 'code',
                    title: '音频编号',
                    align: 'center',
                }, {
                    field: 'format',
                    title: '音频格式',
                    align: 'center'
                }, {
                    field: 'createTime',
                    title: '创建时间',
                    templet: function (d) {
                        return d.createTime == undefined ? '-' : d.createTime.substring(0, 19)
                    },
                    align: 'center'
                }, {
                    field: 'status',
                    title: '状态',
                    width: 120,
                    templet: '#switchTpl',
                    unresize: true,
                    align: 'center'
                },
                {
                    title: '操作',
                    width: 120,
                    align: 'center',
                    templet: function (d) {
                        return `<div class="table-tool ">
                                    <div onclick='delAudio("${d.id}")' class="table-del layui-btn">
                                     <img src="../static/img/del.png">删除
                                    </div>
                                </div>`
                    },
                }
            ]
        ]
        , height: 'full'
        // ,skin: 'line' //表格风格
        , even: true
        , page: { //支持传入 laypage 组件的所有参数（某些参数除外，如：jump/elem） - 详见文档
            groups: 3 //只显示 1 个连续页码
            , first: false //不显示首页
            , last: false //不显示尾页
        }
    });


    layui.form.on('switch(table-status)', function (obj) {

        var id = this.value;
        new AjaxChain()
            .setUrl('/audio/use')
            .setMethod('post')
            .setData(JSON.stringify({
                id: id,
                status: (obj.elem.checked ? 1 : 2)
            }))
            .then(data => {
                layer.msg('操作成功', { icon: 1, time: 1500 });
            })
            .catch(err => {
                console.error('请求异常:', err);
            })
            .send();


    });

}


// 音频操作
function opAudio(type) {

    switch (type) {
        case 1://一键同步

            layer.confirm('确定进行同步操作吗？', { icon: 3 }, function () {

                new AjaxChain()
                    .setUrl('/audio/device/download')
                    .setMethod('post')
                    .enableLayer('同步成功',
                        function () { })
                    .then(data => {
                    })
                    .catch(err => {
                        console.error('请求异常:', err);
                    })
                    .send();
            });

            break;
        case 2://上传音频

            upLoadAudio()

            break;
        case 3://批量删除
            delAudio()
            break;

        default:
            break;
    }
}


//上传音频
var curFile = null;//当前选中的音频
var curIndex = null;
upLoadAudio = () => {
    curFile = null;
    curIndex = layer.open({

        type: 1,

        area: '40%',

        resize: false,

        shadeClose: false,

        title: '上传音频',

        content: `<form class="layui-form layui-form-pane" id="audio-form" lay-filter="audioForm" action="">
                    <div class="form-item">
                        <label class="layui-form-label">音频名称</label>
                        <div class="layui-input-block">
                            <input type="text" name="name" lay-affix="clear" placeholder="请输入" lay-verify="required"  class="layui-input">
                        </div>
                    </div>
                    <div class="form-item">
                        <label class="layui-form-label">音频编号</label>
                        <div class="layui-input-block">
                            <input type="text" name="code" lay-affix="clear" placeholder="请输入"  class="layui-input">
                        </div>
                    </div>
                    <div class="form-item">
                        <label class="layui-form-label">选择文件</label>
                        <div class="layui-input-block">
                             <input type="text" class="layui-input" lay-verify="required" name="file" placeholder="支持mp3、wav、amr、pcm格式" id="file-upload">
                        </div>
                    </div>
                    <div class="form-item pane-tool">
                        <div class="layui-btn layui-edit-submit" lay-submit  lay-filter="audio-save">上传</div>
                    </div>
                </form>`,

        success: function () {

            var upload = layui.upload;

            // 渲染

            upload.render({
                elem: '#file-upload',
                auto: false,
                accept: 'audio',
                acceptMime: 'audio/*',
                exts: 'mp3|wav|amr|pcm',
                done: function (res) {
                },
                choose: function (obj) {

                    obj.preview(function (index, file, result) {

                        curFile = file
                        $("#file-upload").attr('value', file.name)

                    });

                }

            });

            form.render();

            form.on('submit(audio-save)', function (data) {

                var field = data.field;

                var formData = new FormData();

                formData.append('name', field.name);
                formData.append('code', field.code);
                formData.append('file', curFile);

                ajaxUploadFile('/audio/save', upLoadCallBack, formData)
                function upLoadCallBack(res) {
                    if (res.message == "OK") {
                        layer.msg('上传成功', { icon: 1, time: 2000 });
                        curFile = null;
                        queryAudioTable()
                    } else {
                        layer.msg('上传失败', { icon: 2, time: 2000 });
                        curFile = null;
                    }
                    layer.close(curIndex);
                }
                return false; // 阻止默认 form 跳转

            });
        }
    });

}



//删除音频
delAudio = (id) => {

    var ids = []
    if (id) {
        ids.push(id)
    } else {

        var checkStatus = table.checkStatus('record-table');

        var checkedIds = checkStatus.data.map(item => item.id);
        if (checkedIds.length === 0) {
            layer.msg('请至少选择一个音频');
            return
        } else {
            ids = checkedIds
        }

    }



    layer.confirm('确定删除该音频吗？', { icon: 3 }, function () {

        new AjaxChain()
            .setUrl('/audio/delete/batch')
            .setMethod('post')
            .setData(JSON.stringify({
                "ids":
                    ids

            }))
            .then(data => {
                layer.msg('删除成功', { icon: 1, time: 1500 });
                queryAudioTable();
            })
            .catch(err => {
                console.error('请求异常:', err);
            })
            .send();
    });

}



// 广播操作
operateHorn = (type) => {
    var checkStatus = table.checkStatus('table');

    var checkedIds = checkStatus.data.map(item => item.deviceId);


    if (checkedIds.length === 0) {
        layer.msg('请至少选择一个设备');
    } else {

        if (type == 0) {
            curIndex = layer.open({
                type: 1,
                area: '40%',
                resize: false,
                shadeClose: false,
                title: '播放音频',
                content: `<form class="layui-form layui-form-pane" id="operateHorn-form" lay-filter="operateHornForm" action="">
                            <div class="form-item">
                                <label class="layui-form-label">播放类型</label>
                                <div class="layui-input-block">
                                    <input lay-filter="playType-radio" type="radio" name="playType" value="3" title="单次播放" checked> 
                                    <input lay-filter="playType-radio" type="radio" name="playType" value="2" title="单曲循环">
                                    <input lay-filter="playType-radio" type="radio" name="playType" value="4" title="列表播放"> 
                                </div>
                            </div>
                            <div class="form-item">
                                <label class="layui-form-label">音量</label>
                                <div class="layui-input-block">
                                    <input lay-filter="volume-filter" type="radio" name="volume" value=1 lay-skin="none" >
                                    <div lay-radio class="lay-skin-tag layui-badge">1</div>
                                    <input lay-filter="volume-filter" type="radio" name="volume" value=2 lay-skin="none">
                                    <div lay-radio class="lay-skin-tag layui-badge">2</div>
                                    <input lay-filter="volume-filter" type="radio" name="volume" value=3 lay-skin="none">
                                    <div lay-radio class="lay-skin-tag layui-badge">3</div>
                                    <input lay-filter="volume-filter" type="radio" name="volume" value=4 lay-skin="none" checked>
                                    <div lay-radio class="lay-skin-tag layui-badge">4</div>
                                    <input lay-filter="volume-filter" type="radio" name="volume" value=5 lay-skin="none">
                                    <div lay-radio class="lay-skin-tag layui-badge">5</div>
                                    <input lay-filter="volume-filter" type="radio" name="volume" value=6 lay-skin="none">
                                    <div lay-radio class="lay-skin-tag layui-badge">6</div>
                                    <input lay-filter="volume-filter" type="radio" name="volume" value=7 lay-skin="none">
                                    <div lay-radio class="lay-skin-tag layui-badge">7</div>
                                </div>
                            </div>
                            <div class="form-item horn-play horn-play-2 horn-play-3">
                                <label class="layui-form-label">选择音频</label>
                                <div class="layui-input-block">
                                    <select name="audioId" lay-filter="audio-filter"></select>
                                </div>
                            </div>
                            <div class="form-item horn-play horn-play-3"  >
                                <label class="layui-form-label">播放次数</label>
                                <div class="layui-input-block">
                                    <input type="text" name="playCount" lay-affix="clear" placeholder="请输入"   class="layui-input">
                                </div>
                            </div>
                            <div class="form-item pane-tool">
                                <div class="layui-btn layui-edit-submit" lay-submit  lay-filter="operateHorn-save">播放</div>
                            </div>
                        </form>`,

                success: function (index) {

                    new AjaxChain()
                        .setUrl('/audio/list/all?status=1')
                        .then(data => {

                            $('select[name="audioId"]').empty().append(
                                data.reduce((x, y) => {
                                    return x + `<option value="${y.id}">${y.name}</option>`
                                }, '<option value="">请选择</option>')
                            )

                            form.render();

                        })
                        .catch(err => {
                            console.error('请求异常:', err);
                        })
                        .send();


                    form.on('radio(playType-radio)', function (data) {

                        var elem = data.elem;
                        var value = elem.value;

                        $('.horn-play').hide();

                        $('.horn-play-' + value).show();

                    });

                }
            });
        } else {
            operateHornAjax({
                "deviceIds": checkedIds,
                "playType": 5,
            })
        }


    }


}


operateHornAjax = (p) => {

    layer.confirm('确定进行该操作吗？', { icon: 3 }, function () {


        new AjaxChain()
            .setUrl('/horn/save/operate')
            .setMethod('post')
            .setData(JSON.stringify(
                p
            ))
            .then(data => {
                layer.close(curIndex)
                layer.msg('操作成功', { icon: 1, time: 1500 });
            })
            .catch(err => {
                console.error('请求异常:', err);
            })
            .send();
    })

}


//操作记录弹窗
operateTable = () => {
    curEvent = ""
    curDate = ""
    layer.open({
        title: '操作记录',
        type: 1,
        offset: 'r',
        move: false,
        anim: 'slideLeft', // 从右往左
        area: ['100%', '100%'],
        shade: 0.3,
        shadeClose: false,
        id: 'operate-offset',
        success: function (layero, index, that) {
            queryOperateTable()

            layui.laydate.render({
                elem: "#operate-date",
                range: true,
                done: function (value, date, endDate) {
                    curDate = value
                    queryOperateTable()
                }
            });

            form.render();


            form.on('radio(event-filter)', function (data) {



                var value = data.elem.value;
                curEvent = value;
                queryOperateTable()

            });
        },
        content: $('#table-operate').html()
    });
}


// 广播设备历史操作查询
function queryOperateTable() {

    if (curDate != '') {
        var beginTime = curDate.split(' - ')[0]
        var endTime = curDate.split(' - ')[1]
    } else {
        var beginTime = ''
        var endTime = ''
    }
    params.startDate = beginTime
    params.endDate = endTime

    table.render({
        elem: '#operate-table'
        , text: {
            none: '暂无数据'
        }
        , method: 'get'
        , url: ajaxPrefix() + "/horn/list/operate"
        , headers: {
            SessionId: JSON.parse(localStorage.getItem('sessionId'))
        }
        , where: params
        , parseData: function (res) { //res 即为原始返回的数据
            return {
                "code": res.status == 200 ? 0 : 1, //解析接口状态
                "msg": res.message, //解析提示文本
                "count": res.result.total, //解析数据长度
                "data": res.result.data
            };
        }
        , request: {
            pageName: 'pageNum' //页码的参数名称，默认：page
            ,
            limitName: 'pageSize' //每页数据量的参数名，默认：limit
        }
        , cols: [
            [ //表头
                {
                    field: 'address',
                    title: '设备名称',
                    align: 'center',
                }, {
                    field: 'deviceCode',
                    title: '编号',
                    align: 'center'
                }, {
                    field: 'playTypeDesc',
                    title: '操作类型',
                    align: 'center'
                }, {
                    field: 'returnDesc',
                    title: '操作结果',
                    align: 'center',
                }, {
                    field: 'dataTime',
                    title: '操作时间',
                    templet: function (d) {
                        return d.dataTime == undefined ? '-' : d.dataTime.substring(0, 19)
                    },
                    align: 'center'
                }, {
                    field: 'returnTime',
                    title: '反馈时间',
                    templet: function (d) {
                        return d.returnTime == undefined ? '-' : d.returnTime.substring(0, 19)
                    },
                    align: 'center'
                },
            ]
        ]
        , height: 'full'
        // ,skin: 'line' //表格风格
        , even: true
        , page: { //支持传入 laypage 组件的所有参数（某些参数除外，如：jump/elem） - 详见文档
            groups: 3 //只显示 1 个连续页码
            , first: false //不显示首页
            , last: false //不显示尾页
        }
    });

}
